package com.github.shiqiyue.myadmin.util.security;

import com.github.shiqiyue.myadmin.config.SecurityConfig;
import com.github.shiqiyue.myadmin.config.security.common.AuthorityCommon;
import com.github.shiqiyue.myadmin.entity.SessionUser;
import com.github.shiqiyue.myadmin.util.spring.HttpContextUtils;
import com.github.shiqiyue.myadmin.util.web.IpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;

/***
 * 安全工具
 * 
 * @author wwy shiqiyue.github.com
 *
 */
public class SecurityUtils {
	
	public static SessionUser getSessionUser() {
		try {
			return (SessionUser) getAuthentication().getPrincipal();
		} catch (Exception e) {
			return null;
		}
	}
	
	public static Authentication getAuthentication() {
		try {
			return SecurityContextHolder.getContext().getAuthentication();
		} catch (Exception e) {
			return null;
		}
		
	}
	
	/***
	 * 验证权限
	 * 
	 * @param authorityName
	 *            完整权限名称
	 * @return 是否拥有权限
	 */
	public static boolean hasAuthority(String authorityName) {
		try {
			return getAuthentication().getAuthorities().contains(new SimpleGrantedAuthority(authorityName));
		} catch (Exception e) {
			return false;
		}
		
	}
	
	/***
	 * 验证权限
	 * 
	 * @param prefix
	 *            前缀
	 * @param name
	 *            权限名称
	 * @return 是否拥有权限
	 */
	public static boolean hasAuthority(String prefix, String name) {
		return hasAuthority(StringUtils.join(new String[] { prefix, name }, AuthorityCommon.DELIMITER));
	}
	
	/***
	 * 验证权限，自动设置前缀
	 * 
	 * @param authName
	 * @return 是否拥有权限
	 */
	public static boolean auth(String authName) {
		String prefix = (String) HttpContextUtils.getHttpServletRequest()
				.getAttribute(SecurityConfig.AUTHORITY_PREFIX_ATTRIBUTE_NAME);
		return hasAuthority(prefix, authName);
	}
	
	/***
	 * 将userAgent和ip地址和sessionId 一起hash做缓存
	 * 
	 * @param request
	 * @return
	 */
	public static int getLoginInfoHash(HttpServletRequest request) {
		String userAgent = request.getHeader("User-Agent");
		String ipAddress = IpUtils.getIpAddr(request);
		String sessionId = request.getSession().getId();
		int hashResult = (userAgent + ipAddress + sessionId).hashCode();
		return hashResult;
	}
}
